//
//  GuideViewController.swift
//  GuidePage
//
//  Created by Mac on 2021/2/27.
//

import UIKit
private let kSafeBottomHeight: CGFloat = UIDevice.current.isX ? 34.0 : 0
typealias DismissClosure = () -> ()
fileprivate let ImageGuideCell = "GuideCell"

class GuideViewController: UIViewController {

    var images: [UIImage] = [UIImage]() {
        didSet {
            collectionView.reloadData()
        }
    }
    var enterImage: UIImage!
    var dismissClosure: DismissClosure?
    
    fileprivate var collectionView: UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: ImageLayout())
    
    fileprivate var enterBtn: UIButton!
    
    fileprivate var isShowEnterBtn: Bool = false
    var isShowPageControl: Bool = true
    fileprivate var pageControl = UIPageControl()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .clear
        collectionView.backgroundColor = .clear
        collectionView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(GuideCell.self, forCellWithReuseIdentifier: ImageGuideCell)
        view.addSubview(collectionView)
        
        if isShowPageControl {
            pageControl = UIPageControl()
            pageControl.isUserInteractionEnabled = false
            pageControl.hidesForSinglePage = true
            pageControl.numberOfPages = images.count
            pageControl.pageIndicatorTintColor = .lightGray
            pageControl.currentPageIndicatorTintColor = .blue
            view.addSubview(pageControl)
        }
        
        guard let _ = enterImage else {
            isShowEnterBtn = false
            return
        }
        isShowEnterBtn = true
        enterBtn = UIButton(type: .custom)
        
        enterBtn.setImage(enterImage, for: .normal)
        
        enterBtn.sizeToFit()
        enterBtn.center = CGPoint(x: UIScreen.main.bounds.width * 0.5, y: UIScreen.main.bounds.height * 0.875)
        enterBtn.addTarget(self, action: #selector(clickedEnterBtnAction), for: .touchUpInside)
        enterBtn.isHidden = true
        view.addSubview(enterBtn)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let size = pageControl.size(forNumberOfPages: pageControl.numberOfPages)
        pageControl.frame = CGRect(x: (UIScreen.main.bounds.width - size.width)*0.5, y: UIScreen.main.bounds.height - size.height - kSafeBottomHeight, width: size.width, height: size.height)
        
    }

    deinit {
        print("deinit")
    }
}

extension GuideViewController {
    @objc func clickedEnterBtnAction() {
        if dismissClosure != nil {
            dismissClosure!()
        }
    }
}


extension GuideViewController: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return isShowEnterBtn ? images.count : images.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImageGuideCell, for: indexPath) as! GuideCell
        if indexPath.item >= images.count {
            cell.image = nil
        }else {
            cell.image = images[indexPath.item]
        }
        
        return cell
    }
}


extension GuideViewController: UICollectionViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if isShowEnterBtn {
            let offsetX = scrollView.contentOffset.x
            let offset = offsetX / scrollView.frame.width
            enterBtn.isHidden = offset > (CGFloat(images.count - 2) + 0.9) ? false : true
        }
        let current = scrollView.contentOffset.x / scrollView.frame.width
        pageControl.currentPage = lroundf(Float(current))
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if !isShowEnterBtn {
            let offsetX = scrollView.contentOffset.x
            let offset = offsetX / scrollView.frame.width
            if Int(offset) == images.count {
                if dismissClosure != nil {
                    dismissClosure!()
                }
            }
        }
    }
}


class ImageLayout: UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()
        itemSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .horizontal
        
        //设置collectionView的属性
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.bounces = false
        collectionView?.isPagingEnabled = true
    }
}




extension UIDevice {
    /// 是否带有刘海，使用计算属性
    /// - Returns: true带刘海safeArea
    fileprivate var isX: Bool {
        let k_isPad = UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad
        let condition = UIScreen.instancesRespond(to: #selector(getter: UIScreen.main.currentMode))
        if condition {
            //判断iPhoneX，Xs 11pro
            let kiPhone_X = __CGSizeEqualToSize(CGSize(width: 1125, height: 2436), UIScreen.main.currentMode!.size) && !k_isPad
            //判断iPhoneXr 11
            let kiPhone_Xr = __CGSizeEqualToSize(CGSize(width: 828, height: 1792), UIScreen.main.currentMode!.size) && !k_isPad
            //判断iPhoneXsMax 11promax
            let kiPhone_Xs_max = __CGSizeEqualToSize(CGSize(width: 1242, height: 2688), UIScreen.main.currentMode!.size) && !k_isPad
            //判断iPhone12 12pro
            let kiPhone12 = __CGSizeEqualToSize(CGSize(width: 1170, height: 2532), UIScreen.main.currentMode!.size) && !k_isPad
            //判断iPhone12promax
            let kiPhone12_pro_max = __CGSizeEqualToSize(CGSize(width: 1284, height: 2778), UIScreen.main.currentMode!.size) && !k_isPad
            //判断iPhone12mini
            let kiPhone12_mini = __CGSizeEqualToSize(CGSize(width: 1080, height: 2340), UIScreen.main.currentMode!.size) && !k_isPad
            
            if kiPhone12_mini || kiPhone12_pro_max || kiPhone12 || kiPhone_Xs_max || kiPhone_Xr || kiPhone_X {
                return true
            }
        }
        
        return false
    }
}
